package com.woyou.utils;

import java.util.UUID;

import com.woyou.Constant;

import android.app.Activity;
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

/**
 * 设备信息工具类
 * 
 * @author longtao.li
 * 
 */
public class DeviceUtils {

	/**
	 * 获取推送信息token
	 * 
	 * @param context
	 * @return
	 */
	public static String getPushToken(Context context) {
		if (context == null) {
			return null;
		}
		PushTokenPref_ pref = new PushTokenPref_(context);
		String cacheToken = pref.pushToken().get();
		if (!TextUtils.isEmpty(cacheToken)) {
			return cacheToken;
		}
		String Imei = ((TelephonyManager) context
				.getSystemService(Activity.TELEPHONY_SERVICE)).getDeviceId();
		String uuidRaw = UUID.randomUUID().toString().replaceAll("-", "");

		String token;

		token = "AD_" + Imei + "_" + Constant.currentVersion + "_" + uuidRaw;
		token = token.substring(0, 40); // /！！！

		pref.edit().pushToken().put(token).apply();
		return token;
	}

	/**
	 * 获取设备信息
	 * 
	 * @param context
	 * @return
	 */
	public static String getDeviceInfo(Context context) {
		String device_model = Build.MODEL; // 设备型号
		String version_release = Build.VERSION.RELEASE; // 设备的系统版本
		String mac_address = getWiFiMacAdd(context);
		String Imei = ((TelephonyManager) context
				.getSystemService(Activity.TELEPHONY_SERVICE)).getDeviceId();

		String deviceInfo = "AD:Device_" + device_model + ":OS_"
				+ version_release + ":MAC_" + mac_address + ":IDFA_" + ":3G_"
				+ Imei + ":Ver_" + Constant.currentVersion;
		return deviceInfo.replaceAll(" ", "");
	}

	/**
	 * 获取wifi mac地址
	 * 
	 * @param context
	 * @return
	 */
	public static String getWiFiMacAdd(Context context) {
		if (context == null)
			return "";
		WifiManager wifi = (WifiManager) context
				.getSystemService(Context.WIFI_SERVICE);

		WifiInfo info = wifi.getConnectionInfo();

		return info.getMacAddress();
	}

	/**
	 * 友盟获取设备信息的方法
	 * @param context
	 * @return
	 */
	public static String getDeviceInfo_YM(Context context) {
		try {
			org.json.JSONObject json = new org.json.JSONObject();
			android.telephony.TelephonyManager tm = (android.telephony.TelephonyManager) context
					.getSystemService(Context.TELEPHONY_SERVICE);

			String device_id = tm.getDeviceId();

			android.net.wifi.WifiManager wifi = (android.net.wifi.WifiManager) context
					.getSystemService(Context.WIFI_SERVICE);

			String mac = wifi.getConnectionInfo().getMacAddress();
			json.put("mac", mac);

			if (TextUtils.isEmpty(device_id)) {
				device_id = mac;
			}

			if (TextUtils.isEmpty(device_id)) {
				device_id = android.provider.Settings.Secure.getString(
						context.getContentResolver(),
						android.provider.Settings.Secure.ANDROID_ID);
			}

			json.put("device_id", device_id);

			return json.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
